/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.com.minam.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import pe.com.minam.util.ParameterProperties;
import pe.com.minam.util.Util;

/**
 *
 * @author Willian
 */
@Controller
@RequestMapping("/administrador/*")
public class AdminController {

    private static final Logger logger = Logger.getLogger(AdminController.class.getName());

    @Autowired
    private ParameterProperties parameterProperties;

    @RequestMapping(value = "/principal", method = RequestMethod.GET)
    public String getIndex(Model model) {
        return parameterProperties.JSP_ADMIN;
    }

    @RequestMapping(value = "/registrarNoticia", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String insertNoticia(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file");
        String rpta = "";
        if (multipartFile != null) {
            if (!(multipartFile.getContentType().contains("png") || multipartFile.getContentType().contains(
                    "jpeg"))) {
                rpta = "Archivos inv&oacute;lidos...";
            }else{
                try{
                String titulo = request.getParameter("titulo");
                String enlace = request.getParameter("enlace");
                String contenido = request.getParameter("contenido");
                String nombreArchivo = request.getParameter("nombreArchivo");
                String binarios = multipartFile.getBytes().toString();
                logger.info("NOTICIA: "+titulo + "\nEnlace: "+enlace+"\nContenido: "+contenido+"\nArchivo: "+nombreArchivo+"\nBinarios: "+binarios);
                
                nombreArchivo = nombreArchivo.substring(nombreArchivo.lastIndexOf("\\"));
                InputStream myInputStream = new ByteArrayInputStream(multipartFile.getBytes()); 
                crearImagen(myInputStream, nombreArchivo);
                
                }catch(Exception e){
                    logger.info("Error File web: " + e);
                }
            }
        }else{
            rpta = "Error Interno";
        }
        return rpta;
    }
    
    private void crearImagen(InputStream ips,String nombre) {
        String ruta = Util.class.getProtectionDomain().getCodeSource().getLocation().toString();
        File image = new File(ruta + "/images/products/"+nombre);
        logger.info("Archivo a crear : "+(ruta + "/images/products/"+nombre));
        FileOutputStream fos = null;
        byte[] buffer = new byte[1];
        InputStream is = ips;
        try {
            fos = new FileOutputStream(image);
        } catch (FileNotFoundException ex) {
            logger.info("[UPDATE] FILE NOT FOUND");
        }
        try {
            while (is.read(buffer) > 0) {
                fos.write(buffer);
            }
            fos.close();
        } catch (IOException ex) {
            logger.info("[UPDATE] FILE NOT READ BYTES");
        }
    }

}
